package cn.com.picc.tts;

import com.iflytek.ai.platform.api.core.entity.ApiResponse;
import com.iflytek.ai.platform.api.core.enumerate.ApiCodeEnum;
import com.iflytek.ai.platform.api.sdk.common.entity.AppCredential;
import com.iflytek.ai.platform.api.sdk.tts.client.TtsApiClient;
import com.iflytek.ai.platform.api.sdk.tts.entity.TtsRequest;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;

/**
 * @author 曹晟
 * @version v1.00.00
 * @className TTSClient
 * @description TTS模型调用客户端
 * @date 2025/03/28
 **/
public class TTSClient {

    protected TtsApiClient client;

    public TTSClient(String url,
                      String appId,
                      String abilityId,
                      String secretId,
                      String secretKey) {
        final AppCredential credential = new AppCredential(secretId, secretKey, appId);
        // 客户端
        TtsApiClient ttsClient = new TtsApiClient(credential, abilityId, url);
//        ttsClient.enableToAdapter();
        this.client = ttsClient;
    }

    public byte[] invoke(String text,
                  String voiceId,
                  int volume,
                  int speed,
                  int pitch) {
        // 请求体
        TtsRequest request = new TtsRequest(text,voiceId);
        request.setVolume(volume);
        request.setSpeed(speed);
        request.setPitch(pitch);
        ByteArrayOutputStream res = new ByteArrayOutputStream();
        ApiResponse response = client.synthesis(request, res);
        if(ApiCodeEnum.SUCCESS.code() != response.getCode()) {
            System.out.println("Error when use tts model:" + response.getCode() + response.getMessage());
        }
        return res.toByteArray();
    }

    public Boolean invoke(String text,
                         String voiceId,
                         String filePath,
                         int volume,
                         int speed,
                          int pitch) throws Exception {
        TtsRequest request = new TtsRequest(text,voiceId);
        request.setVolume(volume);
        request.setSpeed(speed);
        request.setPitch(pitch);
        FileOutputStream res = new FileOutputStream(filePath);
        ApiResponse response = client.synthesis(request, res);
        if(ApiCodeEnum.SUCCESS.code() != response.getCode()) {
            System.out.println("Error when use tts model:" + response.getCode() + response.getMessage());
        }
        return true;
    }
}